import { NextResponse, type NextRequest } from 'next/server'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { stripe } from '@/app/lib/stripe'; import { sendEmail } from '@/app/lib/email'; import { env } from '@/app/lib/env'; import { displayOrderId } from '@/app/lib/orders'; import { cancellationCustomerHtml, cancellationNoPaymentHtml, cancellationStudioHtml, cancellationStudioInternalHtml } from '@/app/lib/order-emails'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // Cancel an order any time before the customer approves their proof (and // we send it to print). If a payment is on file we issue a full Stripe // refund; if there's NO payment (the order never completed checkout, or // no payment intent was recorded) we still force-cancel it — the customer // doesn't have to do anything — and tell them no payment was found and to // contact the studio if that's wrong. This matches the Refund policy // ("fully refundable before you approve"): a customer can self-cancel // while the order is in the design queue (pending_design) or while a // proof is awaiting their approval (awaiting_approval). Once approved / // in production, cancellation needs different handling and isn't allowed // here. const CANCELLABLE_STATUSES = ['pending_design', 'awaiting_approval', 'revision_requested']; export async function POST( req: NextRequest, ctx: { params: Promise<{ id: string }> }, ) { const { id } = await ctx.params; const user = await getCustomerUser(); if (!user) { return NextResponse.json({ error: 'You must be signed in to cancel an order.' }, { status: 401 }); } const admin = commerceDb(); const { data: order, error: fetchErr } = await admin .from('orders') .select('id, user_id, user_email, status, price_cents, stripe_payment_intent_id, config, updated_at') .eq('id', id) .single(); if (fetchErr || !order) { return NextResponse.json({ error: 'Order not found.' }, { status: 404 }); } if (order.user_id !== user.id) { return NextResponse.json({ error: 'You can only cancel your own orders.' }, { status: 403 }); } const config = (order.config ?? {}) as Record; const previousCancellation = config.customerCancellation as { state?: 'pending' | 'refunded' | 'unpaid' } | undefined; const retry = order.status === 'cancelled' && previousCancellation?.state === 'pending'; if (order.status === 'cancelled' && previousCancellation && !retry) { return NextResponse.json({ ok: true, noPayment: previousCancellation.state === 'unpaid' }); } if (!retry && !CANCELLABLE_STATUSES.includes(order.status)) { return NextResponse.json({ error: `This order can no longer be cancelled — it's already past the design queue. Reach out at hello@lumengesso.com if something's wrong.`, }, { status: 409 }); } if (!retry) { // Claim cancellation before touching Stripe. Approval and cancellation // both compare the status, so only one can win. const { data: claimed, error } = await admin.from('orders') .update({ status: 'cancelled', config: { ...config, customerCancellation: { state: 'pending' } } }) .eq('id', id).eq('user_id', user.id).eq('status', order.status).eq('updated_at', order.updated_at) .select('id').maybeSingle(); if (error || !claimed) { return NextResponse.json({ error: 'The order changed. Reload the order before trying again.' }, { status: error ? 500 : 409 }); } } // If a payment is on file, issue a full refund. If there's NO payment // intent, skip the refund and force-cancel. We never surface raw Stripe // error text to the customer. let refundId: string | null = null; let alreadyRefunded = false; if (order.stripe_payment_intent_id) { try { const refund = await stripe().refunds.create({ payment_intent: order.stripe_payment_intent_id, reason: 'requested_by_customer', metadata: { orderId: order.id, source: 'customer-self-cancel' }, }, { idempotencyKey: `customer-cancellation:${order.id}:${order.stripe_payment_intent_id}` }); if (refund.status === 'failed' || refund.status === 'canceled') throw new Error('Refund was not accepted'); refundId = refund.id; } catch (e) { const errObj = (e ?? {}) as { code?: unknown; message?: unknown }; const code = typeof errObj.code === 'string' ? errObj.code : ''; const emsg = typeof errObj.message === 'string' ? errObj.message : ''; // The charge was already refunded (e.g. manually from the Stripe // dashboard). That's the desired end state — treat it as success and // let the cancel proceed rather than erroring at the customer. if (code === 'charge_already_refunded' || /already been refunded/i.test(emsg)) { alreadyRefunded = true; } else { console.error('[cancel] Stripe refund failed', e); // Friendly, non-technical message — no raw Stripe error. return NextResponse.json({ error: 'The order is cancelled and your photos are saved, but we could not confirm the refund. Retry from this order or contact hello@lumengesso.com.', }, { status: 500 }); } } } const refunded = !!refundId || alreadyRefunded; // Mark the order cancelled. Status transition is the source of truth; // refund evidence (if any) lives on Stripe's side via the payment_intent. const { data: finalized, error: updErr } = await admin.from('orders').update({ config: { ...config, customerCancellation: { state: refunded ? 'refunded' : 'unpaid' } }, }).eq('id', id).eq('user_id', user.id).eq('status', 'cancelled').eq('config->customerCancellation->>state', 'pending') .select('id').maybeSingle(); if (updErr) { console.error('[cancel] DB update failed', updErr); // If a refund already went out, don't fail the response — the money is // back and the row will be reconciled. If there was no refund, the // cancel genuinely didn't persist, so surface the error. return NextResponse.json({ error: 'The order is cancelled. Reload and retry to confirm the refund status.' }, { status: 500 }); } if (!finalized) return NextResponse.json({ ok: true, refundId, noPayment: !refunded }); // Best-effort notifications. Don't fail the cancel flow on email errors. const amount = `$${(order.price_cents / 100).toFixed(2)}`; await Promise.allSettled([ sendEmail({ to: order.user_email, subject: `Cancellation confirmed — ${displayOrderId(order.id)}`, html: refunded ? cancellationCustomerHtml(order.id, order.price_cents) : cancellationNoPaymentHtml(order.id), text: refunded ? `Your commission ${displayOrderId(order.id)} has been cancelled and a full refund of ${amount} has been issued. Funds typically return to your card within 5–10 business days.` : `Your commission ${displayOrderId(order.id)} has been cancelled. We didn't find a completed payment on this order, so there's nothing to refund — you haven't been charged. If you believe this is an error, contact hello@lumengesso.com.`, }), refunded ? sendEmail({ to: env.site.studioEmail(), subject: `Cancelled: ${displayOrderId(order.id)} — ${order.user_email}`, html: cancellationStudioHtml(order.id, order.user_email, order.price_cents), text: `Order ${order.id} cancelled by ${order.user_email}. ${refundId ? `Refund ${amount} issued (Stripe id ${refundId}).` : `Charge was already refunded — no new refund issued.`}`, }) : sendEmail({ to: env.site.studioEmail(), subject: `Cancelled (no payment): ${displayOrderId(order.id)} — ${order.user_email}`, html: cancellationStudioInternalHtml(order.id, order.user_email, order.price_cents, { reason: 'Customer self-cancel — no payment on file', refundId: null, refundError: null, prodigiOrderId: null, }), text: `Order ${order.id} self-cancelled by ${order.user_email}. No payment on file — cancelled without refund.`, }), ]); return NextResponse.json({ ok: true, refundId, noPayment: !refunded }); }